import { RuleStatus, DiscountsMode, DiscountCategory, CalculateType } from '@/constants'
import AmountRule from './components/amount-rule'
import CategoryRule from './components/category-rule'

export default {
  components: {
    AmountRule,
    CategoryRule
  },
  data() {
    return {
      // constants
      RuleStatus,
      DiscountsMode,
      DiscountCategory,
      CalculateType,

      tabsActivity: 'rule',
      showAmountDialog: false,
      showCategoryDialog: false,

      categoryData: [],

      dialogData: {
        mode: 'add', // add | edit
        data: {
          ruleName: '',
          discountMode: 1,
          discountCategory: 2,
          calculateType: '1',
          fullMoney: undefined,
          discountMoney: undefined,
          category: []
        }
      },
      rules: {
        ruleName: [
          { required: true, trigger: 'blur', message: '规则名称不能为空' }
        ],
        fullMoney: [
          { required: true, validator: this.valiFull, message: '满减金额是必选项, 且只能是数字', trigger: 'blur' }
        ],
        discountMoney: [
          { required: true, validator: this.valiSubtract, trigger: 'blur' }
        ],
        category: [
          { required: true, trigger: 'blur', message: '支持类目是必选项', type: 'array' }
        ]
      }
    }
  },
  computed: {
    dialogTitle() {
      return this.dialogData.mode === 'add' ? '添加规则' : '编辑规则'
    },
    dialogBtnTxt() {
      return this.dialogData.mode === 'add' ? '新增' : '修改'
    },
    computeCategorys() {
      return DiscountCategory.filter(cate => {
        if (this.dialogData.data.discountMode === 1) {
          return [1, 2].includes(cate.value)
        } else {
          return [1, 3].includes(cate.value)
        }
      })
    }
  },
  watch: {
    'dialogData.data.discountMode'(val) {
      this.dialogData.data.discountCategory = val === 1 ? 2 : 1
    },
    'dialogData.data.category'(val) {
      console.log(val, 'dialogData.data.category')
    }
  },
  mounted() {
    this.getCategoryData()
  },
  methods: {
    goCategoryList() {
      this.$router.push({
        path: '/market/category'
      })
    },
    triggerDialog(type = 'amount', data) {
      if (type === 'amount') {
        data && (
          this.dialogData.data = {
            ...this.dialogData.data,
            ...this.filldata(data, 'money')
          },
          this.dialogData.mode = 'edit'
        ) || (
          this.initDialogData(),
          this.dialogData.mode = 'add'
        )
        this.showAmountDialog = true
      } else if (type === 'category') {
        const { ruleName, categoryIds, id } = data || {}
        data && (
          this.dialogData.data = {
            id,
            ruleName,
            category: categoryIds.map(d => Number(d))
          },
          this.dialogData.mode = 'edit'
        ) || (
          this.initDialogData(),
          this.dialogData.mode = 'add'
        )
        this.showCategoryDialog = true
      }
    },
    initDialogData() {
      this.dialogData.data = {
        ruleName: '',
        discountMode: 1,
        discountCategory: 2,
        calculateType: '1',
        fullMoney: undefined,
        discountMoney: undefined,
        category: []
      }
    },
    filldata(data, type) {
      if (type === 'money') {
        const { ruleName, discountMode, discountCategory, fullMoney, discountMoney, id } = data
        return {
          ruleName,
          discountMode,
          discountCategory,
          fullMoney,
          discountMoney,
          id
        }
      }
    },
    valiFull(rule, value, callback) {
      const { data: { fullMoney, discountMoney } } = this.dialogData
      const reg = /^[\d\.]+$/

      if (reg.test(fullMoney) && reg.test(discountMoney)) {
        callback()
      } else {
        callback(new Error())
      }
    },
    valiSubtract(rule, value, callback) {
      const reg = /^[\d\.]+$/
      const { data: { discountCategory } } = this.dialogData

      // 折扣时, 取值0-1
      if (discountCategory === 3) {
        if (isNaN(value) || +value < 1 || +value > 10) {
          callback(new Error('折扣时取值只能是1到10'))
        } else {
          callback()
        }
      } else {
        if (reg.test(value)) {
          callback()
        } else {
          callback(new Error('此值是必选项, 并且只能是数字'))
        }
      }
    },
    async getCategoryData() {
      const { success, data } = await this.$api.getCategoryList()
      if (success) {
        this.categoryData = this.mapChildren(data)
      }
    },
    mapChildren(data) {
      return data.map(d => {
        const item = {
          label: d.categoryName,
          value: d.id
        }
        if (d.children && d.children.length) {
          item.children = this.mapChildren(d.children)
        }
        return item
      })
    },
    doSave() {
      this.$refs.$$form.validate(async ok => {
        if (ok) {
          const { ruleName, fullMoney, discountMoney, discountMode, discountCategory, id } = this.dialogData.data
          const params = {
            discountCategory,
            discountMode,
            discountMoney: +discountMoney,
            fullMoney: +fullMoney,
            isActive: 1,
            merchantId: this.$store.getters.customerId,
            ruleName
          }
          if (discountCategory === 3) {
            params.discountMoney = +discountMoney / 10
          }
          if (this.dialogData.mode === 'edit') {
            params.id = id
            delete params.isActive
          }
          try {
            const { success } = await this.$api[this.dialogData.mode === 'add' ? 'addMoneyRule' : 'modifyMoneyRule'](params)
            if (success) {
              this.showAmountDialog = false
              this.$refs.amountPane.refresh()
            }
          } catch (e) {
            this.$message.error('操作失败, 请重试')
          }
        }
      })
    },
    doSaveCategoryRule() {
      this.$refs.$$cate_form.validate(async ok => {
        if (ok) {
          const { ruleName, category, id } = this.dialogData.data
          const params = {
            ruleName,
            categoryIds: category,
            merchantId: this.$store.getters.customerId
          }
          if (this.dialogData.mode === 'edit') {
            params.id = id
          }
          const { success } = await this.$api[this.dialogData.mode === 'add' ? 'addCategoryRule' : 'modifyCategoryRule'](params)
          if (success) {
            this.showCategoryDialog = false
            this.$refs.categoryPane.refresh()
          }
        }
      })
    }
    // -
  }
}
